﻿using AutoMapper;
using ManagementApi.Authorizers;
using ManagementApi.Models;
using ManagementApi.Models.Corp;
using ManagementApi.Mvc;
using ManagementApi.Mvc.ApplicationContexts;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Modules.Constructor;
using Modules.Corp;
using Modules.Project;
using PmSoft.Entity;
using PmSoft.Exceptions;

namespace ManagementApi.Controllers.ConstructorPannel
{
    /// <summary>
    /// 常用业务接口-建设单位角色
    /// </summary>
    [ApiController]
    [Route("/api/v1/constructor/common")]
    [Authorize(Roles = "Constructor")]
    public class CommonController : Controller
    {
        private readonly ConstructorService constructorService;
        private readonly ProjectService projectService;
        private readonly ConstructorApplicationContext applicationContext;
        private readonly IMapper mapper;
 
        public CommonController(ConstructorService constructorService, ProjectService projectService, ConstructorApplicationContext applicationContext, IMapper mapper)
        {
            this.constructorService = constructorService;
            this.applicationContext = applicationContext;
            this.projectService = projectService;
            this.mapper = mapper;
        }

        /// <summary>
        /// 切换项目
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        [HttpPut("projectChanges/{projectId}")]
        public ApiResult ProjectChanges(int projectId)
        {
            if (applicationContext.CurrentUser == null) return ApiResult.Failure("系统异常,请重新登陆");

            #region 验证数据权限

            if (applicationContext.CurrentUser == null) throw new BusinessException("登录信息不存在");
            var projects = projectService.GetProjectInfosByConstructorId(applicationContext.CurrentUser.Id);
            if (!projects.Any(s => s.ProjectId == projectId)) throw new OwnAuthorizationFailedException();

            #endregion 验证数据权限

            ConstructorInfo? constructorInfo = constructorService.GetConstructorInfo(applicationContext.CurrentUser.Id);
            if (constructorInfo == null)
                return ApiResult.Failure("企业信息不存在");
            constructorService.UpdateDefaultProjectId(constructorInfo, projectId);
            return ApiResult.Success("项目切换成功");
        }
    }
}